package com.example.utils;

import java.io.FileInputStream;
import java.util.UUID;

import lombok.experimental.UtilityClass;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;

@Component
public class ImageUtil {

    @Value("${qiniu.accessKey}")
    private String accessKey;

    @Value("${qiniu.accessSecretKey}")
    private String accessSecretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.imageUrl}")
    private String url;

    private UploadManager uploadManager;
    private String token;
    private Auth auth;

    @SuppressWarnings("deprecation")
    public String uploadImageQiniu(FileInputStream file, String key) {

        uploadManager = new UploadManager(new Configuration(Zone.zone2()));
        auth = Auth.create(accessKey, accessSecretKey);
        // 根据命名空间生成的上传token
        token = auth.uploadToken(bucket);

        try {
            // 上传图片文件
            Response res = uploadManager.put(file, key, token, null, null);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
            // 解析上传成功的结果
            DefaultPutRet putRet = JSONUtil.parseObj(res.bodyString()).toBean(DefaultPutRet.class);

            String path = url + "/" + putRet.key;

            // 这个returnPath是获得到的外链地址,通过这个地址可以直接打开图片
            return path;
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return "";
    }

    public String getRandomImgName(String fileName) {
        int index = fileName.lastIndexOf(".");

        if ((fileName == null || fileName.isEmpty()) || index == -1) {
            throw new IllegalArgumentException();
        }
        // 获取文件后缀
        String suffix = fileName.substring(index);
        // 生成UUID
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        // 生成上传至云服务器的路径
        String path = "code/duck/" + DateUtil.today() + "-" + uuid + suffix;
        return path;
    }

}